import { ModelType, StateType } from '@/common-typings';

const tagViews: ModelType = {
  namespace: 'tagView',
  state: {
    curVisitedPath: {},
    cachedViews: [],
  },
  effects: {
    *delAccessViews({ payload, callback }, { put }) {
      yield put({
        type: 'delCheckedViews',
        payload,
      });
      if (callback) callback();
    },
    *delAllViews({ payload, callback }, { put }) {
      yield put({
        type: 'delAllCacheViews',
        payload,
      });
      if (callback) callback();
    },
  },
  reducers: {
    // 保存每次访问的页面
    changeCurAccessPath(state: any, action) {
      return {
        ...state,
        curVisitedPath: action.payload || {},
      };
    },
    // 添加访问的页面
    addAccessViews(state: any, action) {
      if (
        state.cachedViews &&
        state.cachedViews.some((v: StateType) => v.path === action.payload.path)
      ) {
        return { ...state };
      }

      state.cachedViews.push(action.payload);
      return { ...state };
    },
    // 删除访问的页面
    delCheckedViews(state: any, action) {
      let cachedViews: any = [...state.cachedViews];
      cachedViews = cachedViews.filter((i: any) => i.path !== action.payload.path);
      return { ...state, cachedViews };
    },
    // 删除所有的页面
    delAllCacheViews(state, action) {
      return {
        ...state,
        cachedViews: [],
        curVisitedPath: {},
      };
    },
    // 删除其他的页面
    delOtherView(state: any, action) {
      let cachedViews: any = [...state.cachedViews];
      cachedViews = cachedViews.filter((i: any) => i.path === action.payload.path);
      return { ...state, cachedViews };
    },
  },
};

export default tagViews;
